package com.yutel.system.serlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.context.WebApplicationContext;

import com.yutel.system.repository.ExtPanel;
import com.yutel.system.service.impl.ExtPanelService;
import com.yutel.system.struts.extjs.ExtjsEngine;

public class ModelServlet extends HttpServlet {
	private static final long serialVersionUID = 23784723L;

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		this.doPost(request, response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String model = request.getParameter("model");
		System.out.println("model="+ model);
		if(model==null || "".equals(model)) {
			model="1";
		}
		ServletContext sct=request.getSession().getServletContext();
		WebApplicationContext ds=(WebApplicationContext)sct.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
		ExtPanelService extService=(ExtPanelService)ds.getBean("extPanelService");
		ExtPanel pan=new ExtPanel();
		pan.setId(Integer.valueOf(model));
		ExtPanel panel=extService.panel(pan);
		ExtjsEngine ep=new ExtjsEngine();
		ep.make(panel);
//		ep.test2();
		response.setContentType("text/html;charset=UTF-8");
		PrintWriter out = response.getWriter();
		StringBuffer sb=new StringBuffer();
		addHead(sb);
		sb.append(ep.getSb());
		addTail(sb);
		out.println(sb.toString());
		out.flush();
		out.close();
	}
	private void addHead(StringBuffer sb) {
		sb.append("<html>");
		sb.append("<head>");
		sb.append("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">");
		sb.append("</head>");
		sb.append("<body>");
		sb.append("<script type=\"text/javascript\">");
//		sb.append("Ext.onReady(function() { \n");
	}
	private void addTail(StringBuffer sb) {
//		sb.append("\nvar mainPanel = new yutel.mod.modMainPanel({");
//		sb.append("width:Ext.getCmp('content-panel').getActiveTab().getInnerWidth(),");
//		sb.append("height:Ext.getCmp('content-panel').getActiveTab().getInnerHeight()");
//		sb.append("});");
//		sb.append("mainPanel.render('main'); ");
//		sb.append("});");
//		sb.append("</script>");
//		sb.append("<div id='main'></div>");
		sb.append("</body>");
		sb.append("</html>");
	}
}
